package com.ebelter.bodyfatscale.ui.activity;

import android.app.Dialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.os.Message;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import com.ebelter.bodyfatscale.R;
import com.ebelter.bodyfatscale.adapter.MainPagerAdapter;
import com.ebelter.bodyfatscale.common.Constants;
import com.ebelter.bodyfatscale.model.Birthday;
import com.ebelter.bodyfatscale.model.UserInfo;
import com.ebelter.bodyfatscale.model.UserInfoCheckUtil;
import com.ebelter.bodyfatscale.moudules.https.NetUtils;
import com.ebelter.bodyfatscale.moudules.load.LoadData2Service;
import com.ebelter.bodyfatscale.moudules.update.Updater;
import com.ebelter.bodyfatscale.ui.pager.main.BasePagerMain;
import com.ebelter.bodyfatscale.ui.pager.main.DashboardPager;
import com.ebelter.bodyfatscale.ui.pager.main.GoalPager;
import com.ebelter.bodyfatscale.ui.pager.main.InfoPager;
import com.ebelter.bodyfatscale.ui.pager.main.SetPager;
import com.ebelter.bodyfatscale.ui.pager.main.TrendsPager;
import com.ebelter.bodyfatscale.ui.view.dialogs.OfflineTextTipDialog;
import com.ebelter.bodyfatscale.util.NumUtils;
import com.ebelter.bodyfatscale.util.ScaleBaseUtils;
import com.ebelter.bodyfatscale.util.SpecialText;
import com.ebelter.bodyfatscale.util.StatusBarUtil;
import com.ebelter.bodyfatscale.util.StringUtils;
import com.ebelter.bodyfatscale.util.ToastUtil;
import com.ebelter.bodyfatscale.util.UserSpUtil;
import com.ebelter.bodyfatscale.util.ViewUtils;
import com.ebelter.btlibrary.btble.ble.BleManager;
import com.ebelter.btlibrary.btble.ble.BlueToothAgency;
import com.ebelter.btlibrary.btble.ble.bluetooth.callback.ConnectCallback;
import com.ebelter.btlibrary.btble.ble.model.BleType;
import com.ebelter.btlibrary.btble.common.Fields;
import com.ebelter.btlibrary.btble.impl.BtBleManager;
import com.ebelter.btlibrary.btble.impl.scale.ScaleBle;
import com.ebelter.btlibrary.btble.impl.scale.ScaleMessageAnalyser;
import com.ebelter.btlibrary.btble.impl.scale.callback.IMeasureResultCallback;
import com.ebelter.btlibrary.btble.impl.scale.model.OfflineMeasureResult;
import com.ebelter.btlibrary.btble.impl.scale.model.ScaleMeasureResult;
import com.ebelter.btlibrary.btble.impl.scale.model.ScaleUser;
import com.ebelter.btlibrary.btble.impl.scale.upgrade.FirmwareUpgradeCallback;
import com.ebelter.btlibrary.util.SpUtil;
import com.ebelter.btlibrary.util.ULog;
import java.util.ArrayList;
import java.util.List;
import butterknife.BindView;
import butterknife.OnClick;
/**
 * 主页
 */
public class MainActivity extends MonitorBluetoothStatusBaseActivity implements RadioGroup.OnCheckedChangeListener, ViewPager.OnPageChangeListener {

    private static final String TAG = "MainActivity";

    private static final int WHAT_CHECK_HEART = 10;
    private static final int WHAT_DISCONNECT_DEVICE = 11;


    @BindView(R.id.root_rl)
    RelativeLayout root_rl;

    @BindView(R.id.nopairedtiply_root_ll)
    LinearLayout nopairedtiply_root_ll;//没有绑定蓝牙设备的根布局

    private boolean isResum;


    @BindView(R.id.addinfo_root_ll)
    LinearLayout addinfo_root_ll;//没有绑定蓝牙设备的根布局

    private ViewPager vpMain;
    private RadioGroup rgMain;
    private List<BasePagerMain> pagers = new ArrayList<>();
    private MainPagerAdapter mAdapter;
    private ScaleBle mScaleBle;
    private BtBleManager mBtBleManager;
    private UserInfo curUser;
    private ScaleMeasureResult curResult;
    private ScaleUser user;
    private UserInfoCheckUtil mUserInfoCheckUtil;

    private LoadData2Service mLoadData2Service;
    private Updater mUpdater;

    @Override
    protected int loadLayoutById() {
        return R.layout.activity_main;
    }



    @Override
    protected void initViews() {
        vpMain = findViewById(R.id.vp_main);
        rgMain = findViewById(R.id.rg_main);
    }

    @Override
    protected void initData() {
        ULog.i(TAG,"---initData----");
        mLoadData2Service = new LoadData2Service();
       // float c=10/0;
       // mUserInfoCheckUtil.startCheckUserInfo();
        mUserInfoCheckUtil=new UserInfoCheckUtil();
        ViewUtils.goneView(addinfo_root_ll);//先把addInfoView提示信息隐藏起来

        mUpdater=new Updater();

        mUpdater.checkVersion(this,false,true);//检测版本更新

        mBtBleManager = BtBleManager.getInstance(this);

        initUserInfo();

        rgMain.setOnCheckedChangeListener(this);
        vpMain.addOnPageChangeListener(this);
        pagers.clear();
        pagers.add(new GoalPager(this));
        pagers.add(new InfoPager(this));
        pagers.add(new DashboardPager(this));
        pagers.add(new TrendsPager(this));
        pagers.add(new SetPager(this));
        vpMain.setOffscreenPageLimit(5);
        mAdapter = new MainPagerAdapter(pagers);
        vpMain.setAdapter(mAdapter);

        rgMain.check(rgMain.getChildAt(2).getId());//默认选中第二个为主页
        mScaleBle = (ScaleBle) mBtBleManager.switchBle(BleType.SCALE);


//        if (mScaleBle.isDeviceBound()) {
//            ULog.i(TAG, "------initData----device is bound !");
//            startConnectDevice();
//        }
        initDashData();
        initGoalData();
        initSetData();

    }

    @Override
    protected void bluetoothStationReceive(Intent intent, String action) {
        super.bluetoothStationReceive(intent, action);
        if (action.equals(BluetoothAdapter.ACTION_STATE_CHANGED)) {
            int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.ERROR);
            switch (state) {
                case BluetoothAdapter.STATE_OFF:
                    ULog.i(TAG, "STATE_OFF 手机蓝牙关闭");
                  //  BleManager.open(MainActivity.this);
                    ToastUtil.show(R.string.open_blue_tip);//打开蓝牙提示语
                    break;
                case BluetoothAdapter.STATE_TURNING_OFF:
                    ULog.i(TAG, "STATE_TURNING_OFF 手机蓝牙正在关闭");
                    break;
                case BluetoothAdapter.STATE_ON:
                    ULog.i(TAG, "STATE_ON 手机蓝牙开启");
                    break;
                case BluetoothAdapter.STATE_TURNING_ON:
                    ULog.i(TAG, "STATE_TURNING_ON 手机蓝牙正在开启");
                    break;
            }
        }
    }

    private long firstBackTime;
    @Override
    public void onBackPressed() {
        long secondTime = System.currentTimeMillis();
        if (secondTime - firstBackTime > 2000) {
            ToastUtil.show(R.string.Touch_again_to_exit);
            firstBackTime = secondTime;
        } else {
            System.exit(0);
        }
    }

    //断开连接
    public void disConnectDevice(){
        if (mScaleBle!=null){
            mScaleBle.disConnectDevice();
        }
    }

    @Override
    protected void handleMsg(Message msg) {
        switch (msg.what){
            case WHAT_CHECK_HEART:
                checkConnect();
                break;
            case WHAT_DISCONNECT_DEVICE:
                disConnectDevice();
                break;
        }
    }

    int counts;
    private void checkConnect() {
        removeMessages(WHAT_CHECK_HEART);
        sendEmptyMessageDelayed(WHAT_CHECK_HEART,4000);//每隔三秒检查一下的意思
        counts++;

        if(mScaleBle==null){
            ULog.i(TAG,"----checkConnect()---mScaleBle为空");
        }else {
            if (SpUtil.readString(Fields.DEVICE_MAC,null)!=null){
                //说明绑定了
                if (mScaleBle.isConnected()){
                    ULog.i(TAG,"----checkConnect()---设备--已经连接");
                }else {
                    ULog.i(TAG,"----checkConnect()---设备--没有连接");

                    if (!checkAllActivitysResume()){//只要有一个界面可见就返回true
                        ULog.i(TAG,"-----checkConnect()里面检测到没有一个界面是在前台的  这次重新连接设备请求被中止掉--");
                    }else {
                        startConnectDevice();
                    }

                }
            }else {
                ULog.i(TAG,"----checkConnect()---检测到未绑定设备");
               // disConnectDevice();
            }
        }


       // sendUserInfo();//下发用户信息
        //sendHistoryDataRequest();//请求一下离线数据
        //String string="1994-06-18 18:19:32";
        //ScaleBaseUtils.timeFatmat(string,1);
        ULog.i(TAG,"--count="+counts+"---"+ SpecialText.numberLocle(getApplication(),counts));

        //这个是检查数据库里面是否有
        if (mLoadData2Service!=null && counts%3 == 2){
            mLoadData2Service.checkUpLoad(MainActivity.this);
           // mUpdater.checkVersion(MainActivity.this);
        }




    }

    //初始化用户信息
    private void initUserInfo() {
        user=ScaleUser.getUser();
        curUser=new UserInfo();

        String nickName=UserSpUtil.readString(Constants.IUser.NICK_NAME);
        user.setNike(nickName);
        curUser.setName(nickName);

        long usid=UserSpUtil.readLong(Constants.IUser.USER_ID);
        long usid2=usid- 10000000000L;//10个零

        if (usid2<Integer.MAX_VALUE){
            user.setUid((int) usid2);
            curUser.setUid((int) usid2);
        }else {
            user.setUid((int) usid);
            curUser.setUid((int) usid);
        }
        ULog.i(TAG,"--A--usid = "+usid+"--usid2 = "+usid2+"    intmax = " + Integer.MAX_VALUE);


//        String btid=UserSpUtil.readString(Constants.IUser.BT_ID);
//        user.setBtId(btid);
//        curUser.setBtId(btid);

        String bt_id=UserSpUtil.readString(Constants.IUser.BT_ID);
        user.setBtId(bt_id);
        curUser.setBtId(bt_id);

        int age=UserSpUtil.readInt(Constants.IUser.AGE);
        user.setAge(age);
        curUser.setAge(age);

        int sex=UserSpUtil.readInt(Constants.IUser.SEX);
        user.setSex(sex);
        curUser.setSex(sex);

        String birthday=UserSpUtil.readString(Constants.IUser.BIRTHDAY);
        user.setBirthday(birthday);
        Birthday birth=new Birthday();
        birth.setYear(UserSpUtil.readInt(Constants.IUser.YEAR));
        birth.setMonth(UserSpUtil.readInt(Constants.IUser.MONTHS));
        birth.setDay(UserSpUtil.readInt(Constants.IUser.DAY));
        curUser.setBirthday(birth);

        int height=UserSpUtil.readInt(Constants.IUser.HEIGHT);
        user.setHeight(height);
        curUser.setHeight(height);

        float weight = UserSpUtil.readFloat(Constants.IUser.WEIGHT);
        user.setWeight(weight);
        curUser.setWeight(weight);

        float impedance=UserSpUtil.readFloat(Constants.IUser.IMPEDANCE);
        user.setImpedance(impedance);
        curUser.setImpedance(impedance);

        int profession=UserSpUtil.readInt(Constants.IUser.PROFESSION);//角色类型
        user.setRoleType(profession);
        curUser.setRole(profession);

        ULog.i(TAG, "--------initData-----user--" + user);
        ULog.i(TAG, "--------initData-----curUser--" + curUser);
    }


    @Override
    protected void onResume() {
        super.onResume();
        ULog.i(TAG,"---onResume() ");
        isResum = true;
        checkIsBoundDevice();

        removeMessages(WHAT_DISCONNECT_DEVICE);
        startChecks();
    }

    //检测用户信息
    private void checkUserInfo(){
        if (mUserInfoCheckUtil==null){
            return;
        }
        boolean isAll = mUserInfoCheckUtil.startCheckUserInfo();
        if (isAll){
            //说明信息齐全
            ViewUtils.goneView(addinfo_root_ll);
        }else {
            //说明需要补全信息
            ViewUtils.displayView(addinfo_root_ll);
        }

    }

    @Override
    protected void onPause() {
        ULog.i(TAG,"---onPause() ");
        isResum = false;
        removeMessages(WHAT_CHECK_HEART);
        super.onPause();
    }

    @Override
    protected void onStop() {
        super.onStop();
        ULog.i(TAG,"---onStop() ");
        sendEmptyMessageDelayed(WHAT_DISCONNECT_DEVICE,4000);//2秒后断开连接的意思
    }


    private void checkIsBoundDevice() {
        if (!mScaleBle.isDeviceBound()) {
            ULog.i(TAG, "------checkIsBoundDevice----device is not bound");
            ViewUtils.displayView(nopairedtiply_root_ll);
          //  root_rl.setBackgroundColor(Color.parseColor("#cc000000"));
            StatusBarUtil.setDarkStatusIcon(this,false);

        } else {
            ULog.i(TAG, "------checkIsBoundDevice----device is bound !");
            ViewUtils.goneView(nopairedtiply_root_ll);
           /// root_rl.setBackgroundColor(Color.parseColor("#ffffff"));
           // StatusBarUtil.setDarkStatusIcon(this,true);
            checkUserInfo();//先检测是否绑定的状态 然后再检测是否信息完全
        }
    }

    private void initSetData() {
        if (pagers==null||pagers.size()!=5){
            return;
        }
        SetPager setPager= (SetPager) pagers.get(4);
        if (setPager!=null && curUser!=null){
            setPager.initBaseData(curUser.getSex(),curUser.getName(),curUser.geteMail(),curUser.getHeight(),curUser.getBirthday());
        }
    }

    private void initDashData() {
        if (pagers==null||pagers.size()!=5){
            return;
        }
        DashboardPager dashboardPager= (DashboardPager) pagers.get(2);
        if (dashboardPager!=null&&curUser!=null){
            dashboardPager.updateUserNick();
        }
    }

    //初始化Goal数据
    private void switchUnit(int i) {
        if (pagers==null||pagers.size()!=5){
            return;
        }
        BasePagerMain BasePagerMain= pagers.get(i);
        if (BasePagerMain!=null){
            BasePagerMain.switchUnitUpdate();
        }
    }


    //初始化Goal数据
    private void initGoalData() {
        if (pagers==null||pagers.size()!=5){
            return;
        }
        GoalPager goalPager= (GoalPager) pagers.get(0);
        if (goalPager!=null&&curUser!=null){
            goalPager.initBaseData(curUser.getHeight());
        }
    }
    public void goalPagerUpdateCurrentWeight(){
        if (pagers!=null&&pagers.size()>0){
            BasePagerMain basePagerMain = pagers.get(0);
            if (basePagerMain instanceof GoalPager){
                float weight = UserSpUtil.readFloat(Constants.IUser.WEIGHT);
                ((GoalPager) basePagerMain).setCurrentWeight(true,weight);
            }
        }
    }

    //更新TrendsPager下的目标横线
    public void trendPagerUpdateTargetWeight(){
        if (pagers!=null&&pagers.size()>3){
            BasePagerMain basePagerMain = pagers.get(3);
            if (basePagerMain instanceof TrendsPager){
                ((TrendsPager) basePagerMain).displayTargetWeightLine();
            }
        }
    }



    //更新TrendsPager请求平均数据
    public void trendPagerRequestAvgData(boolean scroll2end){
        if (pagers!=null&&pagers.size()>3){
            BasePagerMain basePagerMain = pagers.get(3);
            if (basePagerMain instanceof TrendsPager){
                ((TrendsPager) basePagerMain).requestDisplayData(scroll2end,true);
            }
        }
    }



    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        ULog.i(TAG,"---onActivityResult-----A");

        if (requestCode==ModifyBirthdayActivity.REQUESTCODE){
            //说明修改生日那个界面返回来的
            sendUserInfo();
        }
        if (requestCode==ModifyHeightActivity.REQUESTCODE){
            //说明修改身高那个界面返回来的
            sendUserInfo();
        }




        if (requestCode==DeviceManagerActivity.REQUEST_CODE&&resultCode==DeviceManagerActivity.RESULT_CLEAR_SUCCESS){
            //清除绑定设备成功

            if (mScaleBle!=null){mScaleBle.unbindDevice();}
            disConnectDevice();
            DashboardPager dashboardPager=getDashboardPager();
            if (dashboardPager!=null){
                dashboardPager.onNoResult();
            }
            ULog.i(TAG,"---onActivityResult-----接收到解绑命令");
        }

        if (requestCode==GuestSelectActivity.REQUEST_CODE){
            //说明是选择用户界面返回过来的
            if(resultCode == GuestSelectActivity.SELECT_NOCHANGE){
                ULog.i(TAG,"接收到故--resultCode==GuestSelectActivity.SELECT_NOCHANGE");
                return;
            }else if (resultCode==GuestSelectActivity.SELECT_CURRENT_LOGIN_UER){
                ULog.i(TAG,"接收到故--resultCode==GuestSelectActivity.SELECT_CURRENT_LOGIN_UER");
                Constants.isGuestModel=false;
                ViewUtils.enableRadioGroup(rgMain);
                DashboardPager dashboardPager = getDashboardPager();
                if (dashboardPager!=null){
                    dashboardPager.onNoResult();
                }
                disConnectDevice();

            }else if (resultCode==GuestSelectActivity.SELECT_GUEST){
                ULog.i(TAG,"接收到故--resultCode==GuestSelectActivity.SELECT_GUEST");
                Constants.isGuestModel=true;
                ViewUtils.disableRadioGroup(rgMain);

                UserInfo guestUserInfo= (UserInfo) data.getSerializableExtra(GuestSelectWriteInfoActivity.Key);
                ULog.i(TAG,"guestUserInfo =  "+guestUserInfo);
                setUser(guestUserInfo);

                DashboardPager dashboardPager=getDashboardPager();
                if (dashboardPager!=null){
                    dashboardPager.onNoResult();
                }
                disConnectDevice();
                return;
            }
        }


        if (requestCode==AddUserInfoActivity.REQUEST_CODE){
            ULog.i(TAG,"---onActivityResult-----requestCode==AddUserInfoActivity.REQUEST_CODE--添加用户信息界面返回");

            boolean isAll = mUserInfoCheckUtil.startCheckUserInfo();
            if (isAll){
                //说明信息齐全
                ViewUtils.goneView(addinfo_root_ll);
            }else {
                //说明需要补全信息
                ViewUtils.displayView(addinfo_root_ll);
                return;
            }

        }


        ULog.i(TAG,"---onActivityResult-----B");
        checkIsBoundDevice();

        initUserInfo();
        sendUserInfo();//下发用户信息
        syncSystemClock();//同步时钟
        initSetData();
        initGoalData();
        initDashData();


    }

    //设置用户信息
    private void setUser(UserInfo guestUserInfo) {
        if (guestUserInfo==null){return;}
        ScaleUser scaleUser = ScaleUser.getUser();
        scaleUser.setBtId(guestUserInfo.getBtId());
        scaleUser.setUid(guestUserInfo.getUid());
        scaleUser.setAge(guestUserInfo.getAge());
        scaleUser.setNike(guestUserInfo.getName());
        scaleUser.setBirthday(guestUserInfo.getBirthday().getFatterDay());
        scaleUser.setHeight(guestUserInfo.getHeight());
        scaleUser.setSex(guestUserInfo.getSex());
        scaleUser.setRoleType(guestUserInfo.getRole());
        initDashData();
        sendUserInfo();//下发用户信息
        syncSystemClock();

    }

    //开始连接设备
    private void startConnectDevice() {
        ULog.i(TAG, "------startConnectDevice()----");
        String bondDeviceAddress = SpUtil.readString(com.ebelter.btlibrary.btble.common.Fields.DEVICE_MAC,null);
        if (TextUtils.isEmpty(bondDeviceAddress)){
            ULog.i(TAG, "------startConnectDevice----device is not bound");
            checkIsBoundDevice();
        }else {
            ULog.i(TAG, "------startConnectDevice----"+bondDeviceAddress);
            if (mScaleBle!=null){
                mScaleBle.startConnect(bondDeviceAddress);
            }
        }

    }

    @Override
    protected void onStart() {
        super.onStart();
        //注册连接监听器
        mScaleBle.registerConnectCallback(mConnectCallback);
        //注册测量结果监听器
        mScaleBle.registerMeasureResultCallback(measureResultCallback);
        //注册固件升级监听器  TODO 固件升级监听回调，放在固件升级界面，不放这里，这里只是测试用
        mScaleBle.registerFirmwareUpgradeCallback(mFirmwareUpgradeCallback);

    }



    public void requestDelAllUser(){
        if (mScaleBle!=null){
            mScaleBle.requestDelAllUser();
        }
    }

    //判断设备有没有连接上蓝牙秤
    public boolean scalebleIsConnect(){
        if (mScaleBle!=null){
            return mScaleBle.isConnected();
        }
        return false;
    }

    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        int index = -1;
        switch (checkedId) {
            case R.id.rb_goal://目标体重
                index = 0;
                break;
            case R.id.rb_info://信息
                index = 1;
                break;
            case R.id.rb_dashboard://体重
                index = 2;
                break;
            case R.id.rb_trends://趋势
                index = 3;
                break;
            case R.id.rb_set://设置
                index = 4;
                break;
        }
        if (index >= 0 && index < pagers.size()) {
            vpMain.setCurrentItem(index);
        }
    }

    private void ceshiSwitchUnit() {
        ULog.i(TAG,"当前单位模式------Constants.isKgUnit="+Constants.isKgUnit);
        switchUnit(0);
        switchUnit(2);
        switchUnit(3);
    }


    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {

    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        mScaleBle.unregisterConnectCallback();
        mBtBleManager.releaseOnActivityDestroy();
        mBtBleManager = null;
        mScaleBle = null;
    }

    public void sendUserInfo(){
        if (mScaleBle!=null) {
            mScaleBle.setUserInfo(ScaleUser.getUser());
            ULog.i(TAG,"--------下发了用户数据---"+ScaleUser.getUser());
        }
    }
    private void syncSystemClock(){
        if (mScaleBle!=null) {
            ULog.i(TAG,"--------同步时钟---");
            mScaleBle.syncSystemClock();
        }
    }

    //请求非访客的历史数据
    private void sendHistoryDataRequest(){
        if (!NetUtils.available()){//当网络可以用的时候才去请求离线数据，因为请求回来要立即上传的
            return;
        }
        ScaleUser user=ScaleUser.getUser();
        if (!TextUtils.isEmpty(user.getBtId())&&!TextUtils.equals("0",user.getBtId())){
            if (mScaleBle!=null)
                mScaleBle.requestHistoryRecords(user.getBtId());
            ULog.i(TAG,"--------尝试请求历史数据---user.getBtId()="+user.getBtId());
        }

    }

    //连接状态监听回调
    private ConnectCallback mConnectCallback = new ConnectCallback() {
        @Override
        public void onConnected(BluetoothDevice device) {
            ULog.i(TAG, "------onConnected------");
            if (isResum){
                ToastUtil.show(R.string.tzhchylj);//体脂秤已连接提示
            }

            setDashboardPagerConnectImage(true);
            String DEVICE_Name = SpUtil.readString(Fields.DEVICE_Name);
            if (TextUtils.isEmpty(DEVICE_Name)){
                DEVICE_Name = device.getName();
            }
            ScaleMessageAnalyser.getInstance().connectedBlueName = DEVICE_Name;

        }

        @Override
        public void onScaleWake() {
            ULog.i(TAG, "------onScaleWake------");
            syncSystemClock();
        }

        @Override
        public void onScaleSleep() {
            ULog.i(TAG, "------onScaleSleep------");
            sendHistoryDataRequest();////请求离线数据
        }

        @Override
        public void onDisConnected() {
            ULog.i(TAG, "------onDisConnected------");
            if (isResum){
                ToastUtil.show(R.string.tzhchdklj);//体脂秤断开连接提示
            }

            setDashboardPagerConnectImage(false);
            if (checkAllActivitysResume()){//没有界面显示在前台就没有必要检测了
                startChecks();
            }
        }
    };

    private void setDashboardPagerConnectImage(boolean connectedFlag){
        DashboardPager dashboardPager = getDashboardPager();
        if (dashboardPager!=null){
            dashboardPager.setDashboardPagerConnectImage(connectedFlag);
        }
    }

    private void startChecks(){
        removeMessages(WHAT_CHECK_HEART);
        sendEmptyMessage(WHAT_CHECK_HEART);
    }

    /**
     * 测量结果监听回调
     */
    private IMeasureResultCallback measureResultCallback = new IMeasureResultCallback() {

        @Override
        public void onReceiveMeasureResult(final ScaleMeasureResult result) {
            ULog.i(TAG, "-----onReceiveMeasureResult------result = " + result);
            if (result==null){
                return;
            }
            if (mScaleBle!=null){
                mScaleBle.sendMesureACK();
                ScaleUser.getUser().setImpedance(result.getResistance());
                ScaleUser.getUser().setWeight(result.getWeight());
                mScaleBle.setUserInfo(ScaleUser.getUser());
            }



            curResult = result;
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    if(rgMain!=null&&rgMain.getChildCount() > 3){

                        if ("kg".equals(result.getWeightUnit())){
                            ULog.i(TAG, "-----onReceiveMeasureResult------kg模式1");
                            if (!Constants.isKgUnit){
                                ULog.i(TAG, "-----onReceiveMeasureResult------kg模式2");
                                Constants.isKgUnit = true; //------------------------------------zcq
                                SpUtil.writeBoolean(Constants.IUser.IS_KG_MODEL,true);
                                ceshiSwitchUnit();
                            }
                        }else if ("lb".equals(result.getWeightUnit())){
                            ULog.i(TAG, "-----onReceiveMeasureResult------lb模式1");
                            if (Constants.isKgUnit){
                                ULog.i(TAG, "-----onReceiveMeasureResult------lb模式2");
                                Constants.isKgUnit = false;
                                SpUtil.writeBoolean(Constants.IUser.IS_KG_MODEL,false);
                                ceshiSwitchUnit();
                            }
                        }


                      //  rgMain.check(rgMain.getChildAt(2).getId());
                        BasePagerMain mDashboardPager = pagers.get(2);
                        mDashboardPager.initData(result);
                    }
                }
            });
        }

        @Override
        public void onWeightOverLoad() {
            ULog.i(TAG, "-----onWeightOverLoad------ ");
        }

        @Override
        public void onReceiveHistoryRecord(final OfflineMeasureResult result) {
      //      final OfflineMeasureResult result= (OfflineMeasureResult) ScaleBaseUtils.checkScaleMeasureResult18old(res);
          //  sendHistoryDataRequest();//请求离线数据


            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    if (result==null||mLoadData2Service==null||result.getWeight()<=0){
                        return;//体重都等于0的数据就摒弃掉吧
                    }
                    ULog.i(TAG, "-----onReceiveHistoryRecord------result = " + result.toString());
                    if (result.isSuspectedData()){
                        //是疑义数据 弹框提示
                        OfflineTextTipDialog textTipDialog=new OfflineTextTipDialog(MainActivity.this, StringUtils.getResStr(R.string.Offline_measurements_awaiting_confirmation));
                        textTipDialog.setListener(new OfflineTextTipDialog.ICancelOkBtListener() {
                            @Override
                            public void cancel(Dialog dialogView) {
                                dialogView.cancel();
                            }
                            @Override
                            public void ok(Dialog dialogView) {
                                dialogView.cancel();
                                if (mLoadData2Service!=null){
                                    mLoadData2Service.load(MainActivity.this,MainActivity.this,result,true);
                                    disPlayOffData(result);//离线数据
                                }

                            }
                        });

                        String valueTip = StringUtils.getResStr(R.string.offline_data_value_tip);


                        String weight= NumUtils.numBaoLiuWei(ScaleBaseUtils.adapterDataFloat(result.getWeight()),1)+"";
                        if (Constants.isKgUnit){
                            weight= weight+unitKg;
                        }else {
                            weight=ScaleBaseUtils.unitDisplay2(weight,unitLb);
                        }

                        String time=ScaleBaseUtils.timeFatmat(result.getMeasureTime(),3);
                        textTipDialog.show();
                        textTipDialog.setTip2Str(String.format(valueTip,weight,time));

                    }else {
                        //不是疑义数据，直接上传
                        mLoadData2Service.load(MainActivity.this,MainActivity.this,result,true);
                        disPlayOffData(result);//离线数据
                    }
                }
            });

        }

        //显示离线数据
        public void disPlayOffData(ScaleMeasureResult offScaleMeasureResult){
            if (pagers==null||pagers.size()!=5){
                return;
            }
            BasePagerMain basePagerMain=  pagers.get(2);
            if (basePagerMain!=null&&basePagerMain instanceof DashboardPager){
                ((DashboardPager)basePagerMain).disHistoryMesureData(offScaleMeasureResult);
            }
        }

        @Override
        public void onFatMeasureError(int type) {
            ULog.i(TAG, "-----onFatMeasureError------type = " + type);
            if (ScaleUser.getUser().getAge()<18){
                ToastUtil.show(R.string.select_age_tip);//未满18岁测脂错误提示
            }else {
                ToastUtil.show(R.string.mesure_fat_error_tip);//测脂错误提示
            }


        }

        @Override
        public void onHistoryDownloadDone() {
            ULog.i(TAG, "-----onHistoryDownloadDone------");
        }

        @Override
        public void onReceiveTime(long time) {
            ULog.i(TAG, "-----onReceiveTime------"+time);
            sendUserInfo();//下发用户信息
        }

        @Override
        public void updateUserInfoSuccess() {
            ULog.i(TAG,"设置用户信息成功");
            long CLEAR_ALLUSER_INFO_TIME=SpUtil.readLong(Constants.IUser.CLEAR_ALLUSER_INFO_TIME);
            boolean isShow=SpUtil.readBoolean(Constants.IUser.CLEAR_ALLUSER_INFO_DIALOG_HASSHOW);
            if (System.currentTimeMillis()-CLEAR_ALLUSER_INFO_TIME<2000){
                //说明2秒之前有清空用户的操作
                ULog.i(TAG,"---updateUserInfoSuccess--2秒之前有清空用户的操作");
                sendUserInfo();//重新发一次用户信息
                if (!isShow){
                    SpUtil.writeBoolean(Constants.IUser.CLEAR_ALLUSER_INFO_DIALOG_HASSHOW,true);
                    ToastUtil.show(R.string.clearAllUserInfoSuccess);
                }
            }
          //  sendHistoryDataRequest();//发送请求离线数据
        }

        @Override
        public void sendGetHisDataACK() {
            if (mScaleBle!=null){
            //    ULog.i(TAG, "-----历史数据------接收到了离线数据回应了一个-----ACK");
                mScaleBle.sendGetHistoryACK();}
        }

        @Override
        public void sendGetMesureDataACK() {
            if (mScaleBle!=null){
             //   ULog.i(TAG, "-----测量数据------接收到了测量数据回应了一个-----ACK");
                mScaleBle.sendMesureACK();
            }
        }
    };

    //TODO 固件升级监听回调，放在固件升级界面，不放这里，这里只是测试用
    private FirmwareUpgradeCallback mFirmwareUpgradeCallback = new FirmwareUpgradeCallback() {
        @Override
        public void onUpgradeResponse(int percent) {
            ULog.i(TAG, "-----onUpgradeResponse------percent = " + percent);
        }

        @Override
        public void onUpgradeResult(int result, int type) {
            ULog.i(TAG, "-----onUpgradeResult------result = " + result + ", type = " + type);
        }

        @Override
        public void onLowPower() {
            ULog.i(TAG, "-----onLowPower------");
        }
    };


    @OnClick({ R.id.nopairedtiply_root_ll, R.id.nopairedtiply_pair_now_tv,R.id.addinfo_pair_now_tv})
    public void btClick(View view){
        switch (view.getId()){
            case R.id.nopairedtiply_root_ll://绑定提示界面根布局
                ULog.i(TAG,"----------nopairedtiply_root_ll");
                break;
            case R.id.nopairedtiply_pair_now_tv://绑定提示界面现在绑定按钮
                ULog.i(TAG,"----------nopairedtiply_pair_now_tv");
                if (BlueToothAgency.getInstance().isBluetoothOpen()){
                    Intent mIntent1 = new Intent(this, BindDeviceActivity.class);
                    startActivity(mIntent1);
                }else {
                    Intent mIntent2 = new Intent(this, BindDeviceHintActivity.class);
                    startActivity(mIntent2);
                }
                break;
            case R.id.addinfo_pair_now_tv://补全信息的确定按钮
                ULog.i(TAG,"----------addinfo_pair_now_tv");

                Intent intent=new Intent(MainActivity.this,AddUserInfoActivity.class);
                startActivityForResult(intent,AddUserInfoActivity.REQUEST_CODE);


                break;

        }
    }


    private DashboardPager getDashboardPager(){
        if (pagers!=null&&pagers.size()>2){
            BasePagerMain mDashboardPager = pagers.get(2);
            if(mDashboardPager instanceof DashboardPager){
                return (DashboardPager) mDashboardPager;
            }
        }
        return null;
    }


    @Override
    protected void isAllActivityNoResume() {
        ULog.i(TAG,"检测到所有的界面都在后台了");
//        removeMessages(WHAT_CHECK_HEART);//停止检测的意思
//        sendEmptyMessageDelayed(WHAT_DISCONNECT_DEVICE,3000);//3秒后断开连接的意思
    }
}
